package com.gmics.unifiq.fragment;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.gmics.android.R;
import com.gmics.unifiq.GroupDetail;
import com.gmics.unifiq.controller.GroupController;
import com.gmics.unifiq.entity.Group;

public class GroupFragment extends Fragment {

	private GroupController gc = new GroupController();
	ArrayList<Group> groupList = new ArrayList<Group>();

	private class ListAdapter extends BaseAdapter {

		LayoutInflater inflater;
		ViewHolder viewHolder;

		public ListAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return _groupList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			parent.invalidate();
			convertView = inflater.inflate(R.layout.group_list_row, null);
			viewHolder = new ViewHolder();

			viewHolder.groupNameTV = (TextView) convertView
					.findViewById(R.id.groupNameTV);
			viewHolder.descriptionTV = (TextView) convertView
					.findViewById(R.id.descriptionTV);
			viewHolder.groupIconIV = (ImageView) convertView
					.findViewById(R.id.groupIconIV);
			viewHolder.progBar = (ProgressBar) convertView
					.findViewById(R.id.progBar);

			convertView.setTag(viewHolder);

			viewHolder.groupNameTV.setText(_groupList.get(position).getName());
			viewHolder.descriptionTV.setText(_groupList.get(position)
					.getDescription());

			// Load bitmap from internet
			URL onLineURL;
			try {
				onLineURL = new URL(_groupList.get(position).getImagePath());
				new MyNetworkTask(viewHolder.groupIconIV, viewHolder.progBar)
						.execute(onLineURL);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}

			final int temp = position;
			/*
			 * (convertView.findViewById(R.id.groupRow)) .setOnClickListener(new
			 * OnClickListener() {
			 * 
			 * @Override public void onClick(View arg0) {
			 * 
			 * String _groupName = _groupList.get(temp) .getName().trim();
			 * String _groupdescription = _groupList.get(temp)
			 * .getDescription().trim(); String _groupimagepath =
			 * _groupList.get(temp) .getImagePath().trim();
			 * 
			 * Intent intent = new Intent(getActivity(), GroupDetail.class);
			 * 
			 * Bundle bundle = new Bundle(); bundle.putString("groupName",
			 * _groupName); bundle.putString("groupdescription",
			 * _groupdescription); bundle.putString("groupimagepath",
			 * _groupimagepath); intent.putExtras(bundle);
			 * startActivity(intent);
			 * 
			 * } });
			 */
			return convertView;

		}
	}

	private class MyNetworkTask extends AsyncTask<URL, Void, Bitmap> {

		ImageView tIV;
		ProgressBar pb;

		public MyNetworkTask(ImageView iv, ProgressBar progBar) {
			tIV = iv;
			pb = progBar;
		}// constructor

		@Override
		protected Bitmap doInBackground(URL... urls) {

			Bitmap networkBitmap = null;

			URL networkUrl = urls[0]; // Load the first element
			try {
				networkBitmap = BitmapFactory.decodeStream(networkUrl
						.openConnection().getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}

			return networkBitmap;
		}// return bitmap

		@Override
		protected void onPostExecute(Bitmap result) {
			tIV.setImageBitmap(result);
			tIV.setVisibility(View.VISIBLE);
			pb.setVisibility(View.GONE);
		}// hide progress bar

	}

	private class ViewHolder {
		public TextView groupNameTV;
		public ImageView groupIconIV;
		public TextView descriptionTV;
		public ProgressBar progBar;
	}

	private ListView listview;
	private ArrayList<Group> _groupList = new ArrayList<Group>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.group_layout, container,
				false);

		new LoadGroups().execute();

		return rootView;

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		
		/*
		 * _groupList.clear();
		 * 
		 * ArrayList<Group> groupList = populateGroups();
		 * 
		 * for (int i = 0; i < groupList.size(); i++) {
		 * 
		 * String tname = groupList.get(i).getName(); String tdescription =
		 * groupList.get(i).getDescription(); String turl =
		 * groupList.get(i).getImagePath();
		 * 
		 * Group _GroupModel = new Group(); _GroupModel.setName(tname);
		 * _GroupModel.setDescription(tdescription);
		 * _GroupModel.setImagePath(turl);
		 * 
		 * _groupList.add(_GroupModel); }
		 * 
		 * listview = (ListView) getView().findViewById(R.id.groupList);
		 * listview.setAdapter(new ListAdapter(getActivity()));
		 */
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {


		super.onViewCreated(view, savedInstanceState);
	}

	class LoadGroups extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... args) {
			groupList = gc.retrieveGroups();
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {

			for (int i = 0; i < groupList.size(); i++) {

				int tid = groupList.get(i).getGroupID();
				String tname = groupList.get(i).getName();
				String tdescription = groupList.get(i).getDescription();
				String turl = groupList.get(i).getImagePath();

				Group _GroupModel = new Group();
				_GroupModel.setGroupID(tid);
				_GroupModel.setName(tname);
				_GroupModel.setDescription(tdescription);
				_GroupModel.setImagePath(turl);

				_groupList.add(_GroupModel);
			}

			listview = (ListView) getActivity().findViewById(R.id.groupList);
			ListAdapter myAdapter = new ListAdapter(getActivity());
			listview.setAdapter(myAdapter);
			myAdapter.notifyDataSetChanged();
			
			listview.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int temp,
						long arg3) {

					int _groupID = _groupList.get(temp).getGroupID();
					String _groupName = _groupList.get(temp).getName().trim();
					String _groupdescription = _groupList.get(temp)
							.getDescription().trim();
					String _groupimagepath = _groupList.get(temp).getImagePath()
							.trim();

					Intent intent = new Intent(getActivity(), GroupDetail.class);

					Bundle bundle = new Bundle();
					bundle.putInt("groupid", _groupID);
					bundle.putString("groupname", _groupName);
					bundle.putString("groupdescription", _groupdescription);
					bundle.putString("groupimagepath", _groupimagepath);

					intent.putExtras(bundle);
					startActivity(intent);

					/*
					 * Get back byte[] byteArray =
					 * getIntent().getByteArrayExtra("image"); Bitmap bmp =
					 * BitmapFactory.decodeByteArray(byteArray, 0,
					 * byteArray.length);
					 */
				}
			});
			
		}
	}

}
